<template>
  <div class="app-container">
    <!--    表单查询区-->
    <div class="filter-container">
      <el-input v-model="listQuery.key" placeholder="文件名" style="width: 200px; margin-right: 10px" class="filter-item" clearable @keyup.enter.native="handleFilter" @clear="handleFilter" />
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-upload" @click="dialogFormVisible = true">
        上传
      </el-button>
    </div>

    <!--表格区-->
    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column
        label="ID"
        prop="id"
        width="60px"
        align="center"
      />
      <el-table-column label="文件名" prop="name" align="center" />
      <el-table-column label="文件路径" prop="url" align="center" />
      <el-table-column label="状态·" class-name="status-col" width="100">
        <template v-slot="{row}">
          <el-switch
            v-model="row.state"
            active-color="#13ce66"
            inactive-color="#ff4949"
            :active-value="0"
            :inactive-value="1"
            @change="handleState(row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="150" class-name="small-padding fixed-width">
        <template v-slot="{row}">
          <el-button type="success" size="mini" @click="handleDownload(row)">
            下载
          </el-button>
          <el-button size="mini" type="danger" @click="handleDelete(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--分页插件-->
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.current" :limit.sync="listQuery.size" @pagination="getList" />

    <!--上传文件-->
    <el-dialog title="上传文件" :visible.sync="dialogFormVisible">
      <el-upload
        ref="upload"
        class="upload-demo"
        action="#"
        drag
        :auto-upload="false"
        :http-request="handleUpload"
      >
        <i class="el-icon-upload" />
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="submitUpload">
          上传
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination'
import { deleteFile, downloadFile, getFilePage, updateFileState, uploadFile } from '@/api/file'

export default {
  name: 'File',
  components: { Pagination },
  directives: { waves },
  data() {
    return {
      tableKey: 0,
      // 文件列表
      list: [],
      // 文件列表总数
      total: 0,
      listLoading: true,
      // 查询对象
      listQuery: {
        current: 1,
        size: 20,
        key: ''
      },
      // 表单对话框状态控制 true显示  false隐藏
      dialogFormVisible: false
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 分页获取文件列表
    getList() {
      // 开启加载渲染
      this.listLoading = true
      getFilePage(this.listQuery).then(res => {
        this.list = res.data.records
        this.total = res.data.total
        // 关闭加载渲染
        this.listLoading = false
      }).catch(() => {
        // 请求错误，关闭加载渲染
        this.listLoading = false
      })
    },
    // 搜索处理函数
    handleFilter() {
      this.listQuery.current = 1
      this.getList()
    },
    // 文件上传处理
    handleUpload(request) {
      const formData = new FormData()
      formData.append('file', request.file)
      uploadFile(formData).then(() => {
        this.$refs.upload.clearFiles()
        this.dialogFormVisible = false
        this.getList()
        this.$notify({
          title: '成功',
          message: '文件上传成功',
          type: 'success',
          duration: 2000
        })
      })
    },
    // 上传文件
    submitUpload() {
      this.$refs.upload.submit()
    },
    // 处理文件下载
    handleDownload(row) {
      downloadFile(row.id).then(res => {
        const filename = res.headers['content-disposition']
        const blob = new Blob([res.data])
        const downloadElement = document.createElement('a')
        const href = window.URL.createObjectURL(blob)
        downloadElement.href = href
        downloadElement.download = decodeURIComponent(filename.split('=')[1])
        document.body.appendChild(downloadElement)
        downloadElement.click()
        document.body.removeChild(downloadElement)
        window.URL.revokeObjectURL(href)
      })
    },
    // 处理修改文件状态
    handleState(row) {
      updateFileState(row).then(res => {
        this.$notify({
          title: '成功',
          message: res.msg,
          type: 'success',
          duration: 2000
        })
      }).catch((err) => {
        row.state = row.state === 1 ? 0 : 1
        this.$notify({
          title: '失败',
          message: err,
          type: 'error',
          duration: 2000
        })
      })
    },
    handleDelete(row) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteData(row.id)
      }).catch(() => {
        this.$notify({
          title: '提示',
          message: '已取消删除',
          type: 'info',
          duration: 2000
        })
      })
    },
    // 删除权限信息
    deleteData(id) {
      deleteFile(id).then(res => {
        this.getList()
        this.$notify({
          title: '成功',
          message: res.msg,
          type: 'success',
          duration: 2000
        })
      })
    }
  }
}
</script>

<style scoped>

</style>
